package com.develope.menu;

import org.ksoap2.serialization.PropertyInfo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import com.develope.menu.service.HttpHandler;
import com.develope.menu.service.SoapHelper;
import com.develope.menu.utils.Alerts;
import com.develope.menu.utils.Logger;
import com.develope.menu.utils.Utils;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	

	public final static String EXTRA_MESSAGE = "com.develope.menu.LoginActivity.MESSAGE";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */

	// Values for email and password at the time of the login attempt.
	private String mUser;
	private String mPassword;

	// UI references.
	private EditText mUserView;
	private EditText mPasswordView;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		// Set up the login form.
		
		mUserView = (EditText) findViewById(R.id.user);
		

		mPasswordView = (EditText) findViewById(R.id.password);
		
		
		
		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						if (!isNetworkAvailable()){
							Alerts.showButtonDialog(LoginActivity.this,	getString(R.string.error_connection_failed), null);
						}
						else
						attemptLogin();						
					}
				});	
		
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {

		// Reset errors.
		mUserView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mUser = mUserView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}
		
		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			PropertyInfo[] proInfos = new PropertyInfo[2];
			PropertyInfo proInfo = new PropertyInfo();
			proInfo.setName("username");
			proInfo.setValue(mUser);
			proInfo.setType(String.class);
			proInfos[0]=proInfo;
			proInfo = new PropertyInfo();
			proInfo.setName("pass");
			proInfo.setValue(mPassword);
			proInfo.setType(String.class);
			proInfos[1]=proInfo;
		

			HttpHandler httpHandlerCheckUser = new HttpHandler(
					SoapHelper.METHOD_CHECK_USER, proInfos) {
				@Override
				public void onResponse(int errorCode, String result) {
					View focusView = null;
					
					Alerts.hideLoadingDialog();
					Logger.error("[onResponse] errorCode:" + errorCode + " \n " + result);
					// Logger.error("[onResponse] " + mUser + " - " + mPassword);

					if (TextUtils.isEmpty(result)) {
						Alerts.showButtonDialog(LoginActivity.this,
								"Login Failed! Please try again.", null);
						return;
						}
					

					switch (result) {
					case "True":
						Intent intent = new Intent(LoginActivity.this,MainActivity.class);
						intent.putExtra(EXTRA_MESSAGE, mUser);
						startActivity(intent);						
						return;
						
					case "False":
						Alerts.showNotifyDialog(LoginActivity.this,	"UserName or Password is incorrect! Please try again");
						focusView = mUserView;
						focusView.requestFocus();
						return;
					}
				}

			};

			httpHandlerCheckUser.execute();

		}
	}

	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

}
